import React from 'react';
import { Button, message } from 'antd';
import ProForm, {
  ModalForm,
  ProFormText,
  ProFormSelect,
} from '@ant-design/pro-form';
import { PlusOutlined } from '@ant-design/icons';
import UploadImage from '../UploadImage';



export default function (props: comPropsT) {
  const [formData, setFormData] = React.useState<any>({})
  const forForm = (config: comPropsT['config']) => {
    const dom = new Array();
    Object.keys(config.form).forEach(async (el) => {
      const element = config.form[el]!;
      let proFromType;

      switch (element.type) {
        case 'text':
          proFromType = <ProFormText width="md" name={el} {...element}></ProFormText>;
          break;

        case 'select':
          proFromType = <ProFormSelect width="md" showSearch name={el} {...element} />;
          break;

        case 'upload':
          proFromType = <UploadImage label={element.label} handleChange={(e) => setFormData({ [el]: e.file })
          } />;
          break;

        default:
          break;
      }

      dom.push(<ProForm.Group key={el}>{proFromType}</ProForm.Group>);
    });
    return dom;
  };
  return (
    <ModalForm<{
      name: string;
      company: string;
    }>

      title={props.config.title}
      trigger={
        <Button type="primary">
          <PlusOutlined />
          {props.config.title}
        </Button>
      }
      onFinish={async (values) => {
        const _form = { ...values, ...formData }
        setFormData(_form)
        let is = false
        Object.keys(props.config.form).forEach((el) => {
          const element = props.config.form[el]!;
          if (element.rules && element.rules[0].required && !_form[el]) {
            message.error(element.label + '不能为空');
            return is = true
          }
          return
        })
        if (!is) {
          const res = await props.config.submitBind(_form);
          if (res.code === 200) {
            message.success(res.msg || '添加成功');
            props.updateList();
            return true;
          } else return false
        }
        return true
      }}
    >
      {forForm(props.config)}
    </ModalForm>
  );
};

type comPropsT = {
  config: addPopConfig;
  /** 更新列表 */
  updateList: () => void;
};
